package top.ligongzi.hrm.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

//oauth2授权服务配置类
@Configuration
//启动oauth2授权配置
@EnableAuthorizationServer
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    //=================1 客户端详情：配置客户端请求的参数===========================//
    @Autowired
    private DataSource dataSource;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean //配置客户端详情服务，通过loadClientByClientId传入clientId到oauth_client_details加载客户端详情
    public ClientDetailsService clientDetailsService(){
        JdbcClientDetailsService clientDetailsService
                = new JdbcClientDetailsService(dataSource); //从数据库获取,所以需要数据源
        clientDetailsService.setPasswordEncoder(passwordEncoder); //oauth_client_details数据client_secret是加密，所以需要指定密码加密器
        return clientDetailsService;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
    }


    //=================2 授权服务端点：配置授权码和令牌的管理/存储方式===========================//
    @Autowired
    private AuthenticationManager authenticationManager;
    //2.1 配置授权码服务
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        return new JdbcAuthorizationCodeServices(dataSource);
    }


    private String key = "itsource_hrm&%%$##@@#%%%";
    @Bean //创建jwt访问转换器
    public JwtAccessTokenConverter jwtAccessTokenConverter(){

        //支持两种加密算法：mac(默认)，rsa
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //指定加密秘钥
        jwtAccessTokenConverter.setSigningKey(key);
        return  jwtAccessTokenConverter;
    }

    @Bean
    public TokenStore tokenStore(){

        //return new InMemoryTokenStore();
        //修改为jwttokenStore
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    //2.2 令牌的管理
    @Bean
    public AuthorizationServerTokenServices tokenService(){
        //创建默认的令牌服务
        DefaultTokenServices services = new DefaultTokenServices();
        //指定客户端详情配置
        services.setClientDetailsService(clientDetailsService());
        //支持产生刷新token
        services.setSupportRefreshToken(true);

        //设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        services.setTokenEnhancer(tokenEnhancerChain);  //jwtAccessTokenConverter()

        //token存储方式
        services.setTokenStore(tokenStore());

        //token有效时间2小时
        services.setAccessTokenValiditySeconds(1800);
        //属性令牌默认有效时间
        services.setRefreshTokenValiditySeconds(72000);
        return services;
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //1.密码授权模式需要
        endpoints.authenticationManager(authenticationManager)
        //2.授权码模式服务
        .authorizationCodeServices(authorizationCodeServices())
        //3.配置令牌管理服务
        .tokenServices(tokenService())
        //允许post方式请求
        .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }


    //=================3 配置哪些路径放行(检查token的路径要放行,资源服务要来访问)===========================//
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
        //对应/oauth/check_token ，路径公开
        .checkTokenAccess("permitAll()")
        //允许客户端进行表单身份验证,使用表单认证申请令牌
        .allowFormAuthenticationForClients();
    }

}
